package com.kawa.kemanage.service.impl;

import com.kawa.kemanage.entity.Advertiser;
import com.kawa.kemanage.mapper.AdvertiserMapper;
import com.kawa.kemanage.service.AdvertiserService;
import com.kawa.kemanage.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 广告主服务实现类
 */
@Service
public class AdvertiserServiceImpl implements AdvertiserService {
    @Autowired
    private AdvertiserMapper advertiserMapper;

    @Override
    public List<Advertiser> findAll() {
        return advertiserMapper.findAll();
    }

    @Override
    public PageResult<Advertiser> findByPage(Integer page, Integer size) {
        // 计算偏移量
        int offset = (page - 1) * size;
        // 获取总记录数
        long total = advertiserMapper.count();
        // 获取当前页数据
        List<Advertiser> records = advertiserMapper.findByPage(offset, size);
        // 返回分页结果
        return PageResult.of(records, total, size, page);
    }

    @Override
    public Advertiser findById(Integer id) {
        Advertiser advertiser = advertiserMapper.findById(id);
        if (advertiser == null) {
            throw new RuntimeException("广告主不存在");
        }
        return advertiser;
    }

    @Override
    @Transactional
    public Advertiser create(Advertiser advertiser) {
        if (advertiserMapper.existsByCompanyName(advertiser.getCompanyName())) {
            throw new IllegalArgumentException("公司名称已存在");
        }
        advertiser.setIsDelete(0);
        advertiserMapper.insert(advertiser);
        return advertiser;
    }

    @Override
    @Transactional
    public Advertiser update(Integer id, Advertiser advertiser) {
        if (advertiserMapper.findById(id) == null) {
            throw new RuntimeException("广告主不存在");
        }

        if (advertiserMapper.existsByCompanyNameAndIdNot(
                advertiser.getCompanyName(), id)) {
            throw new IllegalArgumentException("公司名称已存在");
        }

        advertiser.setAdvertiserId(id);
        advertiserMapper.update(advertiser);
        return advertiser;
    }

    @Override
    @Transactional
    public void delete(Integer id) {
        if (advertiserMapper.findById(id) == null) {
            throw new RuntimeException("广告主不存在");
        }
        advertiserMapper.delete(id);
    }
}
